package zisu.algorithm.algorithm.LinkedList;

import zisu.algorithm.algorithm.Queue.Queue;

/**
 * @Author: 蔡翔
 * @Date: 2019/12/6 8:47
 * @Version 1.0
 */
public class LinkedListQueue<E> implements Queue<E> {
    //结点--内部类。
    private class Node{
        private E e;
        private Node next;
        public Node(E e, Node next){
            this.e = e;
            this.next = next;
        }
        public Node(E e){
            this(e,null);
        }
        public Node(){
            this(null,null);
        }

        @Override
        public String toString() {
            return "Node{" +
                    "e=" + e +
                    ", next=" + next +
                    '}';
        }
    }

    //head 指向头结点，tail指向尾结点
    private Node head,tail;
    private int size;
    public LinkedListQueue(){
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void enQueue(E e) {
        if(tail == null){
            tail = new Node(e);
            head = tail;
        }else {
            tail.next = new Node(e);
            tail = tail.next;
        }
        size++;
    }

    @Override
    public E deQueue() {
        if(isEmpty()){
            throw new RuntimeException("Cannot deQueue ,the queue is empty");
        }
        Node retNode = head;
        head = head.next;
        retNode.next = null;
        if(head == null){
            tail = null;
        }
        size--;
        return retNode.e;
    }

    @Override
    public E getFront() throws Exception {
        return head.e;
    }

    @Override
    public Integer getCapacity() {
        if(isEmpty()){
            throw new RuntimeException("Cannot deQueue ,the queue is empty");
        }
        return size;
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        Node cur = head;
        str.append("Queue: front [ ");
        while (cur != null){
            str.append(cur.e+" -> ");
            cur = cur.next;
        }
        str.append("NULL ] tail");
        return str.toString();
    }

    public static void main(String[] args) {
        LinkedListQueue<Integer> queue = new LinkedListQueue<>();
        for(int i=0;i<10;i++){
            queue.enQueue(i);
            System.out.println(queue);

            if(i%3 == 2 ){
                queue.deQueue();
                System.out.println(queue);
            }
        }
    }
}